﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;

namespace HuntingFishGame.H5
{
    public  class GetCode
    {
        //第一次访问的时候，这里不能为空，如果是空，就会报 41001错误 缺少access_token参数
        public static string Code = "WeOkMgd-BYyLu4izUONy1OnYBeg1oq5BYhwoHq3Hd_tDoOyjz2Uuga4gHvsPyTMAJbr8qB8NiUqf-M8Pu7Fd_mr_DalLzgDb0ZDjLvPIOFIucs-pqgC7Lyz6rvBnSV1jAXRdABAROI";
        /// <summary>
        /// 获取a 
        /// </summary>
        public void GetCodeValue()
        {
            #region 获取公众号的密码和唯一ID
            string appid = "";
            string secret = "";

            if(!string.IsNullOrEmpty(Helper.GetConfig("appid")))
            {
                appid = Helper.GetConfig("appid");
            }

            if (!string.IsNullOrEmpty(Helper.GetConfig("secret")))
            {
                secret = Helper.GetConfig("secret");
            }
            #endregion

            if (!string.IsNullOrEmpty(appid) && !string.IsNullOrEmpty(secret))
            {
                //获取access_token
                string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret);

                Helper.ExtLog(url);
                Stream outstream = null;
                Stream instream = null;
                StreamReader sr1 = null;
                Encoding encoding = Encoding.UTF8;
                HttpWebResponse response = null;
                HttpWebRequest request = null;
                try
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                    CookieContainer cookieContainer = new CookieContainer();
                    request.CookieContainer = cookieContainer;
                    request.AllowAutoRedirect = true;
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    outstream = request.GetRequestStream();
                    outstream.Close();
                    //发送请求并获取相应回应数据
                    response = request.GetResponse() as HttpWebResponse;
                    //直到request.GetResponse()程序才开始向目标网页发送Post请求
                    instream = response.GetResponseStream();
                    sr1 = new StreamReader(instream, encoding);

                    //返回结果网页（html）代码
                    string content = sr1.ReadToEnd();

                    JObject jo = (JObject)JsonConvert.DeserializeObject(content);
                    Code = jo["access_token"].ToString();

                    Helper.ExtLog("获取access_token值："+Code);
                    string expires_in = jo["expires_in"].ToString();
                }
                catch (Exception ex)
                {
                    string err = ex.Message;
                }
            }
        }

        /// <summary>
        /// 获取通过url请求微信
        /// </summary>
        public JObject GetUrlJObject(string url)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr1 = null;
            Encoding encoding = Encoding.UTF8;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            try
            {
                request = WebRequest.Create(url) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                outstream = request.GetRequestStream();
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr1 = new StreamReader(instream, encoding);

                //返回结果网页（html）代码
                string content = sr1.ReadToEnd();

                JObject jo = (JObject)JsonConvert.DeserializeObject(content);
                return jo;

            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return null;

            }
        }
    }
}